<script>
import View from "./views/normal";
import {mapGetters, Store} from "vuex";
import {CHOOSE_IMG} from "../../config/postMessage-types";
import {uploadImg} from "./axios";
export default {
    props: {
        //单位：rem
        outerMargin: {
            type: Number,
            default: 0.75
        }
    },
    data() {
        return {
            id: ""
        }
    },
    computed: {
        ...mapGetters("gw", [
            "getFileArray"
        ]),
        fileArray() {
            return this.getFileArray[this.id] || [];
        }
    },
    methods: {
        initId() {
            this.id = parseInt(Math.random() * 10000);
        },
        sendMsg(data) {
            let msg = JSON.stringify(data);
            window.postMessage(msg);
        },
        //上传所选图片
        upload() {
            return new Promise(async resolve => {
                //返回给组件调用者的结果对象
                let returnObj = {
                    status: 2,
                    data: []
                }
                //如果图片为空，点击上传按钮则返回status：2
                if (!this.fileArray.length) {
                    resolve(returnObj);
                    return;
                }
                //开始请求接口，上传图片
                let result = await uploadImg(this.fileArray);
                returnObj.status = result.status;
                returnObj.data = result.data;
                resolve(returnObj);
            });
        },
        //添加按钮的事件
        addBtnEvent() {
            let msg = {
                type: CHOOSE_IMG,
                data: {
                    id: this.id
                }
            }
            console.log("add", msg);
            
            this.sendMsg(msg);
        },
        //删除图片
        deleteImg(index) {
            if (index === undefined) return;
            let fileArray = this.fileArray;
            fileArray.splice(index, 1);
            // store.commit("gw/setFileArray", this.getFileArray.splice(index, 1));
            store.commit("gw/setFileArray", {[this.id]: fileArray});
        }
    },
    created() {
        this.initId();
    },
    render() {
        return (
            <View 
                outerMargin={this.outerMargin}
                fileArray={this.fileArray} 
                addBtnEvent={this.addBtnEvent}
                delete={this.deleteImg}
            />
        )
    }
}
</script>
